package com.opoc.service.Impl;

import com.opoc.mapper.EnterpriseMapper;
import com.opoc.mapper.PoolMapper;
import com.opoc.mapper.WorkshopMapper;
import com.opoc.pojo.Pool;
import com.opoc.pojo.PoolBasic;
import com.opoc.pojo.PoolTest;
import com.opoc.properties.ExcelProperties;
import com.opoc.pojo.Pool_sql;
import com.opoc.service.PoolService;
import com.opoc.utils.ExcelUtils;
import com.opoc.utils.FileUtils;
import com.opoc.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

@Service
@Slf4j
public class PoolServiceImpl implements PoolService {

  @Autowired
  PoolMapper poolMapper;
  @Autowired
  EnterpriseMapper enterpriseMapper;
  @Autowired
  WorkshopMapper workshopMapper;

  /**
   *获取池子基本信息
   */
  @Override
  public List<PoolBasic> getPoolBasicInfo(String company_name, String pool_id, String pool_name) {
    List<Pool_sql> pools_sql = poolMapper.getPoolBasicInfo(company_name,pool_id,pool_name);
    List<PoolBasic> pools = new ArrayList<>();

    String[] ignore = {"start_use_date", "latest_clear_date", "test_date"};

    for (Pool_sql pool_sql : pools_sql){
      PoolBasic pool = new PoolBasic();
//      log.info(pool_sql.toString());
      BeanUtils.copyProperties(pool_sql, pool, ignore);

      //把存在数据库中的时间格式 转换为前端可以理解的时间格式
      pool.setTest_date(TimeUtils.SqlDateToStringDate(pool_sql.getTest_date()));
      pool.setLatest_clear_date(TimeUtils.SqlDateToStringDate(pool_sql.getLatest_clear_date()));
      pool.setStart_use_date(TimeUtils.SqlDateToStringDate(pool_sql.getStart_use_date()));

      //把图片本地存放路径 转为url
      pool.setSewage_treatment_flow_chart(FileUtils.getURLFromPath(pool.getSewage_treatment_flow_chart()));
      pool.setPool_code(FileUtils.getURLFromPath(pool.getPool_code()));

      pools.add(pool);

    }

    return pools;
  }

  /**
   *添加池子
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String addPool(Pool pool) throws ParseException {
    String company_id = pool.getCompany_id();
    String workshop_name = pool.getWorkshop_name();

    if (!enterpriseMapper.validEnterpriseById(pool.getCompany_id())){  //不存在为true
      // 如果添加池子时输入的公司不存在
      return "选择的公司不存在，请到企业管理添加企业";
    } else { //如果存在 判断车间是否存在
      if (!workshopMapper.validateWorkshop(company_id, workshop_name)){ //存在返回true
        //如果不存在 添加车间后 再加池子
        workshopMapper.addWorkshop(company_id, workshop_name);
      } //如果存在 直接添加池子

      Pool_sql pool_sql = new Pool_sql();

      String[] ignore = {"start_use_date", "latest_clear_date", "test_date"};
      BeanUtils.copyProperties(pool, pool_sql, ignore);

      //把前端传来的时间格式 转换为数据库可以存储的时间格式
      pool_sql.setTest_date( TimeUtils.StringDateToSqlDate( pool.getTest_date() ) );
      pool_sql.setLatest_clear_date( TimeUtils.StringDateToSqlDate( pool.getLatest_clear_date() ) );
      pool_sql.setStart_use_date( TimeUtils.StringDateToSqlDate(pool.getStart_use_date() ) );
      pool_sql.setBelong_region(enterpriseMapper.getEnterpriseInfoById(pool.getCompany_id()).getBelong_region());
      poolMapper.addPool(pool_sql);
      return null;
    }
  }

  /**
   * 池子检测信息查询
   */
  @Override
  public List<PoolTest> getPoolDetectionInfo(String company_name, String pool_id, String pool_name) {
    List<Pool_sql> pools_sql = poolMapper.getPoolDetectionInfo(company_name,pool_id,pool_name);
    List<PoolTest> pools = new ArrayList<>();

    String[] ignore = {"start_use_date", "latest_clear_date", "test_date"};

    if (pools_sql == null){
      return null;
    }
    for (Pool_sql pool_sql : pools_sql){
      PoolTest pool = new PoolTest();
      BeanUtils.copyProperties(pool_sql, pool, ignore);

      //把存在数据库中的时间格式 转换为前端可以理解的时间格式
      pool.setTest_date(TimeUtils.SqlDateToStringDate(pool_sql.getTest_date()));

      pools.add(pool);
    }
    return pools;
  }

  /*
  * 批量导入池子
  * */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String importPool(MultipartFile file) throws Exception {

    //excel表格的表头信息 与单元格格式限制 表
    Map<String, String> header = ExcelProperties.PoolHeader;
    //excel表头 - sql 表头 映射表
    Map<String, String> header_sql = ExcelProperties.PoolHeader_sql;

    List<Pool_sql> pools = ExcelUtils.getBeansFromExcel(file, header, header_sql, Pool_sql.class);
//    System.out.println(header);
//    System.out.println(header_sql);
//    System.out.println(pools);
    if (pools == null) {
      return "请求失败,检查文件格式";
    } else {

      //validate enterprise id
      for (Pool_sql pool : pools){
        if(poolMapper.validatePoolById(pool.getPool_id())){
          //删掉已经存储在数据库中的图片
          pools.forEach(pool1 -> {
            FileUtils.deleteFile(pool1.getPool_code());
            FileUtils.deleteFile(pool1.getSewage_treatment_flow_chart());
          });
          return "池子已存在";
        }
        //查询企业id 是否存在
        if (!enterpriseMapper.validEnterpriseById(pool.getCompany_id())) {
          //删掉已经存储在数据库中的图片
          pools.forEach(pool1 -> {
            FileUtils.deleteFile(pool1.getPool_code());
            FileUtils.deleteFile(pool1.getSewage_treatment_flow_chart());
          });
          return "企业不存在,请到企业管理页添加企业";
        }
      }

      for (Pool_sql pool : pools){
        //生成池子二维码
        //pool.setPool_code("");
        if (workshopMapper.validateWorkshop(pool.getCompany_id(), pool.getWorkshop_name())) {
          //车间存在直接添加
          poolMapper.addPool(pool);
        } else {
          workshopMapper.addWorkshop(pool.getCompany_id(), pool.getWorkshop_name());
          poolMapper.addPool(pool);
        }
      }
      return null;
    }
  }

  /**
   * 导出池子
   * */
  @Override
  public String exportPool(List<String> ids) throws IOException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
    List<Pool_sql> pools_sql = new ArrayList<>();

    //根据id 获取所有池子信息
    if (!ids.isEmpty()) {
      for (String id : ids) {
        pools_sql.add(poolMapper.getPoolAllInfoByPoolId(id));
      }
    } else {
      return null;
    }

    //生成excel文件
    String excelPath = ExcelUtils.ExcelGenerator(ExcelProperties.PoolHeader, ExcelProperties.PoolHeader_sql, pools_sql, Pool_sql.class);
    if (excelPath == null){
      return null;
    }
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      public void run() {
        FileUtils.deleteFile(excelPath);
      }
    },60 * 1000);
    //返回excel文件的url访问地址

    return FileUtils.getURLFromPath(excelPath);
  }

  /**com
   * 批量删除池子
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String delete(List<String> pool_ids) {
    System.out.println(pool_ids);
    for (String pool_id : pool_ids){
      Pool_sql pool_sql = poolMapper.getPoolAllInfoByPoolId(pool_id);
      if (pool_sql != null){
        poolMapper.deletePoolById(pool_id);

        //删除本地图片
        FileUtils.deleteFile(pool_sql.getSewage_treatment_flow_chart());
        FileUtils.deleteFile(pool_sql.getPool_code());
      } else {
        return "池子不存在";
      }
    }
    return null;
  }

  /**
   * 上传图片
   */
  @Override
  public Map<String, String> uploadImage(MultipartFile sewage_treatment_flow_chart, MultipartFile pool_code, String pool_id) {
    Map<String, String> result = new HashMap<>();

    String sewage_treatment_flow_chart_path = FileUtils.uploadFile(sewage_treatment_flow_chart);
    String pool_code_path = FileUtils.uploadFile(pool_code);

    poolMapper.uploadImage(sewage_treatment_flow_chart_path, pool_code_path, pool_id);

    result.put("sewage_treatment_flow_chart", FileUtils.getURLFromPath(sewage_treatment_flow_chart_path));
    result.put("pool_code",  FileUtils.getURLFromPath(pool_code_path));
    return result;
  }
}
